package src.E_Thread;

import java.util.concurrent.*;

// 方式三，实现Callable接口创建线程
// 好处：有返回值，可以抛出异常
public class E05_CreateThread_Callable implements Callable<Boolean> {

    private String url;
    private String name;
    public E05_CreateThread_Callable(String url, String name){
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() throws Exception {
        new WebDownloader().downloader(url, name);
        System.out.println(name+" 下载成功！");
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        E01_CreateThread_ThradTest t1 = new E01_CreateThread_ThradTest("https://img-blog.csdn.net/20150309140927553","src\\E_Thread\\1.jpg");
        E01_CreateThread_ThradTest t2 = new E01_CreateThread_ThradTest("https://img-blog.csdnimg.cn/20210512174955123.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NzE1OTQz,size_16,color_FFFFFF,t_70#pic_center","src\\E_Thread\\2.jpg");
        E01_CreateThread_ThradTest t3 = new E01_CreateThread_ThradTest("https://img-blog.csdnimg.cn/20210512175007490.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NzE1OTQz,size_16,color_FFFFFF,t_70#pic_center","src\\E_Thread\\3.jpg");
        // 创建线程池
        ExecutorService es = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> f1 = (Future<Boolean>) es.submit(t1);
        Future<Boolean> f2 = (Future<Boolean>) es.submit(t2);
        Future<Boolean> f3 = (Future<Boolean>) es.submit(t3);
        // 获取结果，这里有bug会报空指针异常
        boolean b1 = f1.get();
        boolean b2 = f2.get();
        boolean b3 = f3.get();
        System.out.println(b1);
        System.out.println(b2);
        System.out.println(b3);
        // 关闭服务
        es.shutdown();
    }
}
